"""
核心事件处理逻辑（可复用）
"""
import json
import jsonschema
from datetime import datetime


class EventHandler:
    """事件处理器"""
    
    # 事件Schema（简化版）
    CLICK_EVENT_SCHEMA = {
        "type": "object",
        "required": ["userId", "eventType", "timestamp"],
        "properties": {
            "userId": {"type": "string"},
            "sessionId": {"type": "string"},
            "eventType": {"type": "string", "enum": ["click", "view", "scroll", "hover"]},
            "elementId": {"type": "string"},
            "elementClass": {"type": "string"},
            "pageUrl": {"type": "string"},
            "timestamp": {"type": "integer"},
            "metadata": {"type": "object"}
        }
    }
    
    def __init__(self, kinesis_client, stream_name):
        """
        初始化
        
        Args:
            kinesis_client: Boto3 Kinesis客户端
            stream_name: Kinesis Stream名称
        """
        self.kinesis = kinesis_client
        self.stream_name = stream_name
    
    def validate_event(self, event):
        """
        验证事件数据
        
        Args:
            event: 事件字典
            
        Raises:
            ValueError: 验证失败
        """
        try:
            jsonschema.validate(instance=event, schema=self.CLICK_EVENT_SCHEMA)
        except jsonschema.ValidationError as e:
            raise ValueError(f"Event validation failed: {e.message}")
    
    def handle_click_event(self, event):
        """
        处理点击事件
        
        Args:
            event: 点击事件字典
            
        Returns:
            处理结果字典
        """
        # 验证事件
        self.validate_event(event)
        
        # 添加处理时间戳
        event['processedAt'] = int(datetime.now().timestamp() * 1000)
        
        # 写入Kinesis
        response = self.kinesis.put_record(
            StreamName=self.stream_name,
            Data=json.dumps(event),
            PartitionKey=event['userId']  # 使用userId作为分区键
        )
        
        return {
            'success': True,
            'sequenceNumber': response['SequenceNumber'],
            'shardId': response['ShardId'],
            'userId': event['userId'],
            'eventType': event['eventType']
        }

